package embyparse.tokenizer;

import java.util.ArrayList;

import org.apache.commons.lang3.StringEscapeUtils;

/**
 * The StringDummifier replaces things enclosed in quotes with placeholder strings so that
 * they will pass the tokenizer unchanged. After the tokenizer splits up tokens, the StringDummifier
 * then converts the placeholder strings back to their original values.
 * <br>
 * Dummy strings look like: ��dummystr__$$.
 * @author Justin
 *
 */
public class StringDummifier {

	public static void main(String[] args){
		String src = "hello there, \"blah\", poop, \"blah\"   pppppp blah poop \"poopy\" \"sss\" \"blah poop\"";
		StringDummifier s = new StringDummifier();
		System.out.println(src);
		String dum = s.dummify(src);
		System.out.println(dum);
		String dedum = s.dedummify(dum);
		System.out.println(dedum);
	}

	ArrayList<DummyStr> dummies = new ArrayList<DummyStr>(0);

	//static String quote_dummy = ""+(char)222;
	/**
	 * Replace strings with a dummy string that is immune to punctuation splitting used to parse code.
	 * After code is split, run dedummify on each piece to restore original semantics.
	 * @param source
	 * @return
	 */
	public String dummify(String source){
		source = StringEscapeUtils.unescapeJava(source);
		//source = source.replaceAll("\\\"", quote_dummy );
		int i = source.indexOf('\"');
		if( i!=-1){
			while( i!=-1){

			int i2 = source.indexOf('\"',i+1);
			//L.println("Index of first quote: ",i, ", index of second: ",i2);
			String s = source.substring(i,i2+1);
			String dummy = generateDummy();
			DummyStr d = new DummyStr(dummy,s);
			source = source.replace(s,dummy);
			dummies.add(d);

			//L.println("new source: "+source);
			i = source.indexOf('"');
			}
			return source;
		}
		else return source;
	}

	/**
	 * Restores dummy strings with their original values.
	 * @param source
	 * @return
	 */
	public String dedummify(String source){
		for(int i = 0; i<dummies.size(); i++){
			source = source.replace(dummies.get(i).dummy, (dummies.get(i).real));
		}
		return source;
	}

	/**
	 * Restores dummy strings with their original values.
	 * @param source
	 * @return
	 */
	public String[] dedummify(String... strs){
		for(int i = 0; i<strs.length; i++){
			strs[i] = dedummify(strs[i]);
		}
		return strs;
	}

	int count = 0;
	public String generateDummy(){
		count++;
		//int randint = 100000+(int)(899999*Math.random());
		return "��dummystr"+count+"��";
	}
}

class DummyStr{
	public String dummy;
	public String real;
	public DummyStr(String d, String r){
		dummy = d;
		real = r;
	}
}